package com.yllt4cloud.common.ddbase.util;


import com.yllt4cloud.common.core.util.ResultResp;
import com.yllt4cloud.common.ddbase.annotation.RegexType;
import com.yllt4cloud.common.ddbase.constant.ErrorCode;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.lang.reflect.Field;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;


/*
 * EEfuse
 * @author Sean Lai
 * @version 1.0,2010/12/7
 * Copyright (c) 2010.
 */


public class ValidateService {
    private static final Log logger = LogFactory.getLog(ValidateService.class);
//    private static com.manager.com.framework.json.annotation.Field field;


    //解析的入口
    public static ResultResp validate(Object object){
        //获取object的类型
        Class<? extends Object> clazz = object.getClass();
        //获取该类型声明的成员
        Field[] fields = clazz.getDeclaredFields();
        //遍历属性
        for (Field field : fields) {
            //对于private私有化的成员变量，通过setAccessible来修改器访问权限
            field.setAccessible(true);
            ResultResp resultResp = validate(field, object);
            //重新设置回私有权限
            field.setAccessible(false);
            if (resultResp != null) {
                return resultResp;
            }
        }
        return null;
    }

    public static ResultResp validate(Field field, Object object){
        String description;
        Object value=null;


        //获取对象的成员的注解信息

        com.yllt4cloud.common.ddbase.annotation.Field dv = field.getAnnotation(com.yllt4cloud.common.ddbase.annotation.Field.class);
//            value = field.get(object);
        

        if (dv == null) {
            return null;
        }
        value = ReflectionUtils.getFieldValue(object, field.getName());
        description = dv.description().equals("") ? field.getName() : dv.description();
        if (!dv.nullable()) {
        	
        	
            if (value == null || StringUtil.isBlank(value.toString())) {
                return ResultResp.fail(description + "不能为空", ErrorCode.PARAMETER_NO_MATCH);
            }
            
            if(value != null && value instanceof Collection){
        		if(value == null || ((Collection)value).size() < 1)
        			return ResultResp.fail(description + "不能为空", ErrorCode.PARAMETER_NO_MATCH);
        	}
        }else if(dv.nullable()){
        	if (value == null || StringUtil.isBlank(value.toString())) {
        		return null;
        	}
        }
        
     	//复杂对象校验
        if(value instanceof Collection){
            Iterator it=((Collection) value).iterator();

            ResultResp resultResp = null;
            while (it.hasNext()) {
            	resultResp = validate(it.next());
            	
            	if(resultResp != null)
            		return resultResp;
            }
            
            return null;
        } else if(value != null && !isJavaClass(value.getClass())){//非系统自定义类型  即用户自定义数据类型
        	
        	ResultResp resultResp = null;
        	resultResp = validate(value);
        	
        	if(resultResp != null)
        		return resultResp;
        	
        	return null;
        }
        
        if (value.toString().length() > dv.maxLength() && dv.maxLength() != 0) {
            return ResultResp.fail(description + "长度不能超过" + dv.maxLength(), ErrorCode.PARAMETER_NO_MATCH);
        }
        if (value.toString().length() < dv.minLength() && dv.minLength() != 0) {
            return ResultResp.fail(description + "长度不能小于" + dv.minLength(), ErrorCode.PARAMETER_NO_MATCH);
        }
        if (dv.regexType() != RegexType.NONE) {
            switch (dv.regexType()) {
                case NONE:
                    break;
                case SPECIALCHAR:
                    if (RegexUtils.hasSpecialChar(value.toString())) {
                        return ResultResp.fail(description + "不能含有特殊字符", ErrorCode.PARAMETER_NO_MATCH);
                    }
                    break;
                case CHINESE:
                    if (RegexUtils.isChinese2(value.toString())) {
                        return ResultResp.fail(description + "不能含有中文字符", ErrorCode.PARAMETER_NO_MATCH);
                    }
                    break;
                case EMAIL:
                    if (!RegexUtils.isEmail(value.toString())) {
                        return ResultResp.fail(description + "email格式不正确", ErrorCode.PARAMETER_NO_MATCH);
                    }
                    break;
                case IP:
                    if (!RegexUtils.isIp(value.toString())) {
                        return ResultResp.fail(description + "ip地址格式不正确", ErrorCode.PARAMETER_NO_MATCH);
                    }
                    break;
                case NUMBER:
                    if (!RegexUtils.isNumber(value.toString())) {
                        return ResultResp.fail(description + "不是数字", ErrorCode.PARAMETER_NO_MATCH);
                    }
                    break;
                case PHONENUMBER:
                    if (!RegexUtils.isPhoneNumber(value.toString())) {
                        return ResultResp.fail(description + "不是手机号码", ErrorCode.PARAMETER_NO_MATCH);
                    }
                    break;
                case TIME:
                    if (!RegexUtils.isTime(value.toString())) {
                        return ResultResp.fail(description + "不是时间格式", ErrorCode.PARAMETER_NO_MATCH);
                    }
                    break;
                case DATE:
                	if(value instanceof Date){
                        value = DateFormatUtils.format((Date)value, "yyyy-MM-dd");
//                		value = DateUtils.formatDate((Date)value, "yyyy-MM-dd");
                	}
                    if (!RegexUtils.isDate(value.toString())) {
                        return ResultResp.fail(description + "不是日期格式", ErrorCode.PARAMETER_NO_MATCH);
                    }
                    break;
                case DATETIME:
                	if(value instanceof Date){
                        value = DateFormatUtils.format((Date)value, "yyyy-MM-dd HH:mm:ss");
//                		value = DateUtils.formatDate((Date)value, "yyyy-MM-dd HH:mm:ss");
                	}
                	if (!RegexUtils.isDateTime(value.toString())) {
                		return ResultResp.fail(description + "不是日期时间格式", ErrorCode.PARAMETER_NO_MATCH);
                	}
                	break;
                case TELEPHONE:
                	if (!RegexUtils.isTelephone(value.toString())) {
                		return ResultResp.fail(description + "不是固话格式", ErrorCode.PARAMETER_NO_MATCH);
                	}
                	break;
                case ZERO_OR_ONE:
                	if (!RegexUtils.isZeroOrOne(value.toString())) {
                		return ResultResp.fail(description + "不是0或者1", ErrorCode.PARAMETER_NO_MATCH);
                	}
                	break;
                default:
                    break;
            }
        }
        if (!dv.regexExpression().equals("")) {
            if (!value.toString().matches(dv.regexExpression())) {
                return ResultResp.fail(description + "格式不正确", ErrorCode.PARAMETER_NO_MATCH);
            }
        }
        return null;
    }
    
    private static boolean isJavaClass(Class<?> clz) {     
        return clz != null && clz.getClassLoader() == null;     
    }  
}
